package com.ihighest.app.infox.activity;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.adapter.BusinessPagerAdapter;
import com.ihighest.app.infox.adapter.ImagePagerAdapter;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.AutoScrollViewPager;
import com.ihighest.app.infox.tools.InitShare;
import com.umeng.socialize.bean.SHARE_MEDIA;

/**
 * 
 * BusinessOpportunityActivity
 * 
 * <pre>
 * Description: 
 * 商机百科界面
 * </pre>
 * 
 * <pre>
 * Example:
 * </pre>
 * 
 * @author yyh Created at 2015-10-13 下午8:46:04
 * @version 1.0
 */
public class BusinessOpportunityActivity extends BaseActivity implements OnClickListener {

	final String TAG = "BusinessOpportunityActivity";

	String id;// 内容ID
	boolean fav;// 是否收藏

	private ActivityTitle title;
	WebView businessWebView;

	AutoScrollViewPager businessViewPager;
	BusinessPagerAdapter businessPagerAdapter;
	private SHARE_MEDIA shareTo;
	String shearcontent = "";

	private InitShare share;

	// mark
	// private ImageView firstmarkImageView;
	// private ImageView secondmarkImageView;
	// private ImageView thirdmarkImageView;
	// private ImageView foremarkImageView;
	// private ImageView fivemarkImageView;

	private TextView titleTextView;

	private PopupWindow mPopupWindow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.infox_activity_businessopportunities);

		id = super.getIntent().getStringExtra("id");
		fav = super.getIntent().getBooleanExtra("fav", false);

		loadData();
		initView();

	}

	private void loadData() {
		Api.data("wiki/" + id + ".json", new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {
				try {
					String title = result.getData().getString("title");
					shearcontent = title;
					titleTextView.setText(title);
					String content = result.getData().getString("content");
					businessWebView.loadData(content, "text/html; charset=UTF-8", null);

					JSONArray images = result.getData().getJSONArray("images");
					if (images != null && images.length() > 0) {
						String[] urls = new String[images.length()];
						for (int i = 0; i < images.length(); i++) {
							urls[i] = images.getString(i);
						}
						businessViewPager.setVisibility(View.VISIBLE);
						businessViewPager.setAdapter(new ImagePagerAdapter(mContext, urls).setInfiniteLoop(true));
						businessViewPager.setInterval(4000);
						businessViewPager.startAutoScroll();
						businessViewPager.setCurrentItem(Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % images.length());
					} else {
						businessViewPager.setVisibility(View.GONE);
					}

					// if (imagejsonArray == null || imagejsonArray.length() ==
					// 0) {
					// findViewById(R.id.rl_thumbnail).setVisibility(View.GONE);
					// } else {
					// findViewById(R.id.rl_thumbnail).setVisibility(View.VISIBLE);
					// for (int i = 0; i < imagejsonArray.length(); i++) {
					// images.add(imagejsonArray.get(i).toString());
					// }
					// }

				} catch (JSONException e) {
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {
				Log.e(TAG, msg, e);
			}
		}, this);
	}

	private void initView() {
		title = (ActivityTitle) findViewById(R.id.infox_businiss_Title);
		title.setTitle("详情");

		title.setOtherImg(R.drawable.infox_title_share);
		if (fav) {
			title.setSecondImg(R.drawable.infox_content_collection_perss);
		} else {
			title.setSecondImg(R.drawable.infox_person_get);
		}

		title.setViewVersible(title.titleBack, title.titleOther, title.titleSearch, title.rightLayout);
		title.setViewGone(title.titleRefresh, title.titleMsg);

		title.titleSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (TextUtils.isEmpty(SharedPreferencesKit.getString(BusinessOpportunityActivity.this, Const.SP_KEY_USER_ID))) {

					Intent intent = new Intent(BusinessOpportunityActivity.this, LoginActivity.class);
					startActivity(intent);

				} else {

					if (!fav) {

						favorite("1");

					} else {

						favorite("2");
					}
				}
			}
		});
		title.titleOther.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				initSharePupoVindow();
				showPupop();
			}
		});
		share = new InitShare(this);

		titleTextView = (TextView) findViewById(R.id.id_business_title);

		businessWebView = (WebView) findViewById(R.id.id_business_webview);
		businessViewPager = (AutoScrollViewPager) findViewById(R.id.id_businessViewPager);

		// businessListViewAdapter = new BusinessListViewAdapter(this);

		// businessListView.setAdapter(businessListViewAdapter);

		// firstmarkImageView = (ImageView) findViewById(R.id.id_mark1);
		// secondmarkImageView = (ImageView) findViewById(R.id.id_mark2);
		// thirdmarkImageView = (ImageView) findViewById(R.id.id_mark3);
		// foremarkImageView = (ImageView) findViewById(R.id.id_mark4);
		// fivemarkImageView = (ImageView) findViewById(R.id.id_mark5);
		//
		// businessViewPager.setOnPageChangeListener(new OnPageChangeListener()
		// {
		//
		// @Override
		// public void onPageSelected(int arg0) {
		// // TODO Auto-generated method stub
		//
		// firstmarkImageView.setImageResource(R.drawable.infox_mark_n);
		// secondmarkImageView.setImageResource(R.drawable.infox_mark_n);
		// thirdmarkImageView.setImageResource(R.drawable.infox_mark_n);
		// foremarkImageView.setImageResource(R.drawable.infox_mark_n);
		// fivemarkImageView.setImageResource(R.drawable.infox_mark_n);
		// // TODO Auto-generated method stub
		// switch (arg0 % 5) {
		// case 0:
		// firstmarkImageView.setImageResource(R.drawable.infox_mark_y);
		//
		// break;
		// case 1:
		// secondmarkImageView.setImageResource(R.drawable.infox_mark_y);
		// break;
		// case 2:
		// thirdmarkImageView.setImageResource(R.drawable.infox_mark_y);
		// break;
		// case 3:
		// foremarkImageView.setImageResource(R.drawable.infox_mark_y);
		// break;
		// case 4:
		// fivemarkImageView.setImageResource(R.drawable.infox_mark_y);
		// break;
		//
		// }
		//
		// }
		//
		// @Override
		// public void onPageScrolled(int arg0, float arg1, int arg2) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void onPageScrollStateChanged(int arg0) {
		// // TODO Auto-generated method stub
		//
		// }
		// });
		//
	}

	protected void favorite(final String action) {
		// TODO Auto-generated method stub
		Api.post("me/favorite", ApiParam.create().addParam("id", id).addParam("type", "5").addParam("action", action), new ApiCallback(
				this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				// TODO Auto-generated method stub
				if (action.equals("1")) {
					title.setSecondImg(R.drawable.infox_content_collection_perss);
					fav = true;

				} else if (action.equals("2")) {
					title.setSecondImg(R.drawable.infox_person_get);
					fav = false;
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub

			}
		}, this);

	}

	private void initSharePupoVindow() {

		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.infox_activity_content_share_popu, null);

		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		// 必须设置背景
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */
		popupWindow.findViewById(R.id.shareToWeixin).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToFriendCircle).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToMessage).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToQQ).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToWeb).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareEmail).setOnClickListener(this);
		popupWindow.findViewById(R.id.transpond).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareCopyLink).setOnClickListener(this);
		popupWindow.findViewById(R.id.cancle).setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		String url = "http://info.nzdb.com.cn/app";
		if (!TextUtils.isEmpty(SharedPreferencesKit.getString(BusinessOpportunityActivity.this, Const.SP_KEY_USER_ID))) {
			try {
				url = SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_CONFIG_JSON).getString("downAppUrl") + "?code="
						+ SharedPreferencesKit.getString(this, Const.USER_InvitedCode) + "&mid="
						+ SharedPreferencesKit.getString(this, Const.SP_KEY_USER_MID);
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
			}

		}

		switch (view.getId()) {
		case R.id.shareToWeixin:
			shareTo = SHARE_MEDIA.WEIXIN;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToFriendCircle:
			shareTo = SHARE_MEDIA.WEIXIN_CIRCLE;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToMessage:
			shareTo = SHARE_MEDIA.SMS;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToQQ:
			shareTo = SHARE_MEDIA.QQ;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToWeb:
			shareTo = SHARE_MEDIA.SINA;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareEmail:
			shareTo = SHARE_MEDIA.EMAIL;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.transpond:
			ToastKit.showShort(getApplicationContext(), Const.UN_FINISH_ALERT);

			break;
		case R.id.shareCopyLink:
			ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			if (Build.VERSION.SDK_INT >= 11) {
				ClipData clipData = ClipData.newPlainText("App下载链接", url);
				clip.setPrimaryClip(clipData);
			} else {
				clip.setText(url);
			}

			break;
		case R.id.cancle:
			mPopupWindow.dismiss();
			break;

		}
	}

	private void showPupop() {

		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			mPopupWindow.showAtLocation(findViewById(R.id.id_parent), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
		}

	}

}
